package com.zw.a.basic.a14.demo07_tcp_exercise;

//案例: 服务端：接收到数据 写入到文件中.

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

//自定义的TCP协议的服务器端
public class ServerDemo {
    public static void main(String[] args) throws IOException {
        //1. 创建服务器端的Socket对象.
        ServerSocket server = new ServerSocket(10010);
        //2. 监听客户端连接.
        Socket accept = server.accept();

        //3. 获取输入流, 可以读取客户端写过来的数据.
        //InputStream is = accept.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(accept.getInputStream()));

        //4. 定义字符输出流, 关联目的地文件.
        BufferedWriter bw = new BufferedWriter(new FileWriter("day14/data/1.txt"));

        //5. 读取客户端写过来的数据, 并打印.
        String line;
        while((line = br.readLine()) != null) {
            System.out.println(line);           //目标就是把line的值写到文件中即可.

            //6. 把接收到的数据写入到目的地文件中.
            bw.write(line);
            bw.newLine();
        }

        //7. 关闭创建的字符输出流.
        bw.close();

        //8. 关闭Socket对象.
        accept.close();
    }
}
